package com.david.mydemo.ctl_webservice;


import com.alibaba.fastjson.JSONObject;
import com.david.mydemo.util.DateUtils;
import com.david.mydemo.util.StringUtils;
import com.david.mydemo.util.XmlParserUtil;
import com.david.mydemo.ctl_webservice.dao.WsUserDao;
import com.david.mydemo.ctl_webservice.req.UserInfo;
import com.david.mydemo.ctl_webservice.req.UserModifyReqBody;
import com.david.mydemo.ctl_webservice.req.UserModifyRequest;
import com.david.mydemo.ctl_webservice.req.UserModifyRequestInfo;
import com.david.mydemo.ctl_webservice.rsp.UserModifyResponse;
import com.david.mydemo.ctl_webservice.rsp.UserModifyResponseInfo;
import com.david.mydemo.ctl_webservice.rsp.UserModifyRspBody;
import com.david.mydemo.ctl_webservice.rsp.UserModifyRspHead;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.jws.WebService;
import java.util.Map;

/**
 * @author
 */
@WebService(serviceName = "UpdateAppAcctSoap",
        targetNamespace = "http://ctl_webservice.mydemo.david.com/",
        endpointInterface = "com.david.mydemo.ctl_webservice.UserInfoWebService",
        portName = "UpdateAppAcctSoap"
)
//@WebService
@Slf4j
public class UserInfoWebServiceImpl implements UserInfoWebService {

    //应用标识
    @Value("${cop.sso4a.serviceId: GSNGGIS}")
    private String serviceId;

    @Autowired
    private WsUserDao wsUserDao;


//    @Override
//    public WsUserInfo getWsUserInfo(String userId) {
//        System.out.println("---------------------------------userId--------------------------- : " + userId);
//        WsUserInfo wsUserInfo = new WsUserInfo();
//        wsUserInfo.setUserId(userId);
//        wsUserInfo.setUserAccount("张姗姗");
//        wsUserInfo.setUserPw("123456");
//        wsUserInfo.setUserAge(26);
//        wsUserInfo.setUserSex("男");
//        wsUserInfo.setUserName("张姗姗");
//        return wsUserInfo;
//    }

    @Override
    public String UpdateAppAcctSoap(String requestInfoXml) {
        log.info("同步更新用户数据xml，{}", requestInfoXml);
        UserInfo userInfo = null;
        // add新增、delete删除、change修改、chgstatus加/解锁、resetpwd重置密码
        String modifyMode = null;
        try {
            requestInfoXml = "<USERMODIFYREQ>" + requestInfoXml.split("<USERMODIFYREQ>")[1];
            UserModifyRequestInfo requestInfo = XmlParserUtil.parseFromXml(requestInfoXml, UserModifyRequestInfo.class);
            if (requestInfo == null) {
                return userModifyResponseError("9", "", "解析报文，转换xml数据为对象为空");
            }
            UserModifyReqBody userModifyReqBody = requestInfo.getUserModifyReqBody();
            if (userModifyReqBody == null) {
                return userModifyResponseError("9", "", "解析报文，获取xml对象[BODY]节点为空");
            }
            if (!serviceId.equals(requestInfo.getUserModifyReqHead().getServiceid())) {
                return userModifyResponseError("9", "", "解析报文，获取xml对象[HEAD].[SERVICEID]节点，内容非法");
            }
            userInfo = userModifyReqBody.getUserInfo();
            if (userInfo == null) {
                return userModifyResponseError("9", "", "解析报文，获取xml对象[BODY].[USERINFO]节点为空");
            }
            if (StringUtils.isEmpty(userInfo.getUserId())) {
                return userModifyResponseError("9", "", "解析报文，获取xml对象[BODY].[USERINFO].[USERID]节点为空");
            }
            modifyMode = userModifyReqBody.getModifyMode();
            if (StringUtils.isEmpty(modifyMode)) {
                return userModifyResponseError("9", "", "解析报文，获取xml对象[BODY].[MODIFYMODE]节点为空");
            }
        } catch (Exception e) {
            log.error("解析报文出错", e);
            return userModifyResponseError("9", "", "解析报文出错");
        }

        try {
            if ("add".equalsIgnoreCase(modifyMode)) {
                Map<String, Object> user = wsUserDao.get4aUserById(userInfo.getUserId());
                if (user != null && user.get("user_id") != null) {
                    return userModifyResponseError("9", userInfo.getUserId(), "用户[" + userInfo.getUserId() + "]已经存在");
                }
                wsUserDao.insert4aUser(userInfo);
            } else if ("delete".equalsIgnoreCase(modifyMode)) {
                wsUserDao.delete4aUser(userInfo.getUserId());
            } else if ("change".equalsIgnoreCase(modifyMode)) {
                wsUserDao.change4aUser(userInfo);
            } else if ("chgstatus".equalsIgnoreCase(modifyMode)) {
                if ("1".equals(userInfo.getStatus())) {
                    wsUserDao.able4aUser(userInfo);
                } else if ("0".equals(userInfo.getStatus())) {
                    wsUserDao.disable4aUser(userInfo);
                } else {
                    return userModifyResponseError("9", userInfo.getUserId(), "用户状态[" + userInfo.getStatus() + "]传入非法参数");
                }
            } else if ("resetpwd".equalsIgnoreCase(modifyMode)) {
                wsUserDao.resetpwd4aUser(userInfo);
            } else {
                return userModifyResponseError("9", userInfo.getUserId(), "变更模式[" + modifyMode + "]传入非法参数");
            }

            return userModifyResponseSuccess("0", userInfo.getUserId(), userInfo.getLoginNo(), modifyMode, "");
        } catch (Exception e) {
            log.error("系统异常", e);
            return userModifyResponseError("9", userInfo.getUserId(), "系统异常");
        }
    }

    @Override
    public UserModifyResponse UpdateAppAcctSoap1(UserModifyRequest requestInfo) {
        log.info("同步更新用户数据，{}", JSONObject.toJSONString(requestInfo));
        UserModifyResponse userModifyResponse = new UserModifyResponse();
        UserModifyResponseInfo userModifyResponseInfo = new UserModifyResponseInfo();
        UserModifyRspHead userModifyRspHead = new UserModifyRspHead();
//        userModifyRspHead.setCode("000");
//        userModifyRspHead.setSid("000");
        userModifyRspHead.setTimestamp(DateUtils.dateTimeNow());
        userModifyRspHead.setServiceid(serviceId);
        userModifyResponseInfo.setUserModifyRspHead(userModifyRspHead);
        userModifyResponse.setUserModifyResponseInfo(userModifyResponseInfo);

        UserInfo userInfo = null;
        // add新增、delete删除、change修改、chgstatus加/解锁、resetpwd重置密码
        String modifyMode = null;
        try {
//            UserModifyRequestInfo requestInfo = XmlParserUtil.parseFromXml(requestInfoXml, UserModifyRequestInfo.class);
            if (requestInfo == null) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，转换xml数据为对象为空");
            }
            UserModifyRequestInfo userModifyRequestInfo = requestInfo.getUserModifyRequestInfo();
            if (userModifyRequestInfo == null) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，转换xml对象[USERMODIFYREQ]节点为空");
            }
            UserModifyReqBody userModifyReqBody = userModifyRequestInfo.getUserModifyReqBody();
            if (userModifyReqBody == null) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，获取xml对象[BODY]节点为空");
            }
            if (!serviceId.equals(userModifyRequestInfo.getUserModifyReqHead().getServiceid())) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，获取xml对象[HEAD].[SERVICEID]节点，内容非法");
            }
            userInfo = userModifyReqBody.getUserInfo();
            if (userInfo == null) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，获取xml对象[BODY].[USERINFO]节点为空");
            }
            if (StringUtils.isEmpty(userInfo.getUserId())) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，获取xml对象[BODY].[USERINFO].[USERID]节点为空");
            }
            modifyMode = userModifyReqBody.getModifyMode();
            if (StringUtils.isEmpty(modifyMode)) {
                return userModifyResponseError(userModifyResponse, "9", "", "解析报文，获取xml对象[BODY].[MODIFYMODE]节点为空");
            }
        } catch (Exception e) {
            log.error("解析报文出错", e);
            return userModifyResponseError(userModifyResponse, "9", "", "解析报文出错");
        }

        try {
            if ("add".equalsIgnoreCase(modifyMode)) {
                Map<String, Object> user = wsUserDao.get4aUserById(userInfo.getUserId());
                if (user != null && user.get("user_id") != null) {
                    return userModifyResponseError(userModifyResponse, "9", userInfo.getUserId(), "用户[" + userInfo.getUserId() + "]已经存在");
                }
                wsUserDao.insert4aUser(userInfo);
            } else if ("delete".equalsIgnoreCase(modifyMode)) {
                wsUserDao.delete4aUser(userInfo.getUserId());
            } else if ("change".equalsIgnoreCase(modifyMode)) {
                wsUserDao.change4aUser(userInfo);
            } else if ("chgstatus".equalsIgnoreCase(modifyMode)) {
                if ("1".equals(userInfo.getStatus())) {
                    wsUserDao.able4aUser(userInfo);
                } else if ("0".equals(userInfo.getStatus())) {
                    wsUserDao.disable4aUser(userInfo);
                } else {
                    return userModifyResponseError(userModifyResponse, "9", userInfo.getUserId(), "用户状态[" + userInfo.getStatus() + "]传入非法参数");
                }
            } else if ("resetpwd".equalsIgnoreCase(modifyMode)) {
                wsUserDao.resetpwd4aUser(userInfo);
            } else {
                return userModifyResponseError(userModifyResponse, "9", userInfo.getUserId(), "变更模式[" + modifyMode + "]传入非法参数");
            }

            return userModifyResponseSuccess(userModifyResponse, "0", userInfo.getUserId(), userInfo.getLoginNo(), modifyMode, "");
        } catch (Exception e) {
            log.error("系统异常", e);
            return userModifyResponseError(userModifyResponse, "9", userInfo.getUserId(), "系统异常");
        }
    }

    @Override
    public String UpdateAppAcctSoap11(UserModifyRequest requestInfo) {
        log.info("测试更新用户数据：" + JSONObject.toJSONString(requestInfo));
        return "word";
    }

    private UserModifyResponse userModifyResponseSuccess(UserModifyResponse userModifyResponse,
                                                         String rsp, String userId, String loginNo, String modifyMode, String errDesc) {
        UserModifyResponseInfo userModifyResponseInfo = userModifyResponse.getUserModifyResponseInfo();
        UserModifyRspBody userModifyRspBody = new UserModifyRspBody();
        userModifyRspBody.setRsp(rsp);
        userModifyRspBody.setUserId(userId);
        userModifyRspBody.setLoginNo(loginNo);
        userModifyRspBody.setModifyMode(modifyMode);
        userModifyRspBody.setErrDesc(errDesc);
        userModifyResponseInfo.setUserModifyRspBody(userModifyRspBody);
        String parse2Xml = XmlParserUtil.parse2Xml(userModifyResponse, UserModifyResponse.class);
        log.info("同步更新用户数据成功，请求xml参数：{}", parse2Xml);
//        return "<?xml version='1.0' encoding='UTF-8'?>" + parse2Xml;
//        return parse2Xml;
        return userModifyResponse;
    }

    private UserModifyResponse userModifyResponseError(UserModifyResponse userModifyResponse,
                                                       String rsp, String key, String errDesc) {
        UserModifyResponseInfo userModifyResponseInfo = userModifyResponse.getUserModifyResponseInfo();
        UserModifyRspBody userModifyRspBody = new UserModifyRspBody();
        userModifyRspBody.setRsp(rsp);
        userModifyRspBody.setKey(key);
        userModifyRspBody.setErrCode("");
        userModifyRspBody.setErrDesc(errDesc);
        userModifyResponseInfo.setUserModifyRspBody(userModifyRspBody);
        String parse2Xml = XmlParserUtil.parse2Xml(userModifyResponse, UserModifyResponse.class);
        log.error("同步更新用户数据出错，错误信息：{}，请求xml参数：{}", errDesc, parse2Xml);
//        return "<?xml version='1.0' encoding='UTF-8'?>" + parse2Xml;
//        return parse2Xml;
        return userModifyResponse;
    }

    private String userModifyResponseSuccess(String rsp, String userId, String loginNo, String modifyMode, String errDesc) {
        String rspXml = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<USERMODIFYRSP>" +
                "<HEAD>" +
                "<CODE>000</CODE>" +
                "<SID>000</SID>" +
                "<TIMESTAMP>" + DateUtils.dateTimeNow() + "</TIMESTAMP>" +
                "<SERVICEID>" + serviceId + "</SERVICEID>" +
                "</HEAD>" +
                "<BODY>" +
                "<MODIFYMODE>" + modifyMode + "</MODIFYMODE>" +
                "<USERID>" + userId + "</USERID>" +
                "<LOGINNO>" + loginNo + "</LOGINNO>" +
                "<RSP>" + rsp + "</RSP>" +
                "<ERRDESC>" + errDesc + "</ERRDESC>" +
                "</BODY>" +
                "</USERMODIFYRSP>";
        log.info("同步更新用户数据成功，响应xml参数：{}", rspXml);
        return rspXml;
    }

    private String userModifyResponseError(String rsp, String key, String errDesc) {
        String rspXml = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<USERMODIFYRSP>" +
                "<HEAD>" +
                "<CODE>000</CODE>" +
                "<SID>000</SID>" +
                "<TIMESTAMP>" + DateUtils.dateTimeNow() + "</TIMESTAMP>" +
                "<SERVICEID>" + serviceId + "</SERVICEID>" +
                "</HEAD>" +
                "<BODY>" +
                "<KEY>" + key + "</KEY>" +
                "<ERRCODE></ERRCODE>" +
                "<ERRDESC>" + errDesc + "</ERRDESC>" +
                "</BODY>" +
                "</USERMODIFYRSP>";
        log.error("同步更新用户数据出错，错误信息：{}，响应xml参数：{}", errDesc, rspXml);
        return rspXml;
    }

}
